<template>
  <div class="teacher-workload">
    <div class="page-header">
      <h2>工作量统计</h2>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" :inline="true" class="filter-form">
        <el-form-item label="学期">
          <el-select
            v-model="filterForm.semester"
            placeholder="请选择学期"
            clearable
            style="width: 200px"
            @change="handleSemesterChange"
          >
            <el-option label="2024春季" value="2024春季" />
            <el-option label="2024秋季" value="2024秋季" />
            <el-option label="2025春季" value="2025春季" />
            <el-option label="2025秋季" value="2025秋季" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="fetchWorkloadStats">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计概览 -->
    <el-row :gutter="20" class="stats-overview">
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon stat-icon-calendar">
              <el-icon><Calendar /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ workloadStats.totalHours || 0 }}</div>
              <div class="stat-label">总课时</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon stat-icon-reading">
              <el-icon><Reading /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ workloadStats.courseCount || 0 }}</div>
              <div class="stat-label">授课门数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon stat-icon-user">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ workloadStats.studentCount || 0 }}</div>
              <div class="stat-label">学生人数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon stat-icon-chart">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ workloadStats.avgWeeklyHours || 0 }}</div>
              <div class="stat-label">平均周课时</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细统计 -->
    <el-card class="workload-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>详细统计</span>
          <el-button type="success" @click="exportData">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
        </div>
      </template>
      
      <el-table
        :data="courseDetails"
        v-loading="loading"
        stripe
        border
        show-summary
        :summary-method="getSummaries"
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="courseName" label="课程名称" width="150" />
        <el-table-column prop="className" label="班级" width="180">
          <template #default="scope">
            <el-tag type="info">{{ scope.row.className }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="courseType" label="课程类型" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.courseType === '必修' ? 'primary' : 'success'">
              {{ scope.row.courseType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="credits" label="学分" width="80" align="center" />
        <el-table-column prop="totalHours" label="总学时" width="100" align="center" />
        <el-table-column prop="completedHours" label="已完成" width="100" align="center" />
        <el-table-column prop="remainingHours" label="剩余" width="100" align="center" />
        <el-table-column prop="studentCount" label="学生数" width="100" align="center">
          <template #default="scope">
            <el-tag type="success" size="large">{{ scope.row.studentCount }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="进度" width="150" align="center">
          <template #default="scope">
            <el-progress 
              :percentage="scope.row.progress" 
              :color="getProgressColor(scope.row.progress)"
              :stroke-width="18"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 周课时分布 -->
    <el-card class="chart-card" shadow="hover">
      <template #header>
        <span>周课时分布</span>
      </template>
      
      <div class="chart-container">
        <div class="bar-chart">
          <div 
            v-for="week in weeklyDistribution" 
            :key="week.week" 
            class="bar-item"
          >
            <div class="bar-wrapper">
              <div 
                class="bar" 
                :style="{ height: getBarHeight(week.hours) + '%' }"
              >
                <div class="bar-value">{{ week.hours }}</div>
              </div>
            </div>
            <div class="bar-label">第{{ week.week }}周</div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Calendar, Reading, User, TrendCharts, Download } from '@element-plus/icons-vue'
import { getTeacherWorkloadStats } from '../api/teacherUser'

// 筛选表单
const filterForm = reactive({
  semester: '2024春季'
})

// 加载状态
const loading = ref(false)

// 工作量统计数据
const workloadStats = ref({
  totalHours: 0,
  courseCount: 0,
  studentCount: 0,
  avgWeeklyHours: 0,
  courseDetails: [],
  weeklyDistribution: []
})

// 课程详情列表
const courseDetails = computed(() => {
  return workloadStats.value.courseDetails || []
})

// 周课时分布
const weeklyDistribution = computed(() => {
  return workloadStats.value.weeklyDistribution || []
})

// 获取工作量统计数据
const fetchWorkloadStats = async () => {
  loading.value = true
  
  try {
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    const teacherId = user.teacherId || user.teacher_id || user.teId || user.id
    
    console.log('===== 获取工作量统计 =====')
    console.log('教师ID:', teacherId)
    console.log('学期:', filterForm.semester)
    
    if (!teacherId) {
      ElMessage.error('请先登录')
      return
    }

    const response = await getTeacherWorkloadStats(teacherId, filterForm.semester || '2024春季')
    console.log('API响应:', response)
    
    if (response && response.data) {
      workloadStats.value = response.data
      console.log('===== 工作量统计数据 =====')
      console.log('原始响应:', response)
      console.log('工作量数据:', workloadStats.value)
      console.log('课程详情列表:', workloadStats.value.courseDetails)
      console.log('课程详情数量:', workloadStats.value.courseDetails ? workloadStats.value.courseDetails.length : 0)
      
      if (workloadStats.value.courseDetails && workloadStats.value.courseDetails.length > 0) {
        console.log('详细课程信息:')
        workloadStats.value.courseDetails.forEach((detail, index) => {
          console.log(`  ${index + 1}. ${detail.courseName} - ${detail.className} - 学生数: ${detail.studentCount}`)
        })
        ElMessage.success(`加载成功，共 ${workloadStats.value.courseDetails.length} 条记录`)
      } else {
        ElMessage.warning('未获取到课程详情数据')
      }
    } else {
      ElMessage.warning('未获取到数据')
      console.error('响应数据格式错误:', response)
    }
    
  } catch (error) {
    console.error('获取工作量统计失败:', error)
    ElMessage.error('获取工作量统计失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 学期改变
const handleSemesterChange = () => {
  console.log('学期改变:', filterForm.semester)
  fetchWorkloadStats()
}

// 重置
const handleReset = () => {
  filterForm.semester = '' // 重置为全部学期
  fetchWorkloadStats()
}

// 导出数据
const exportData = () => {
  if (!courseDetails.value || courseDetails.value.length === 0) {
    ElMessage.warning('暂无数据可导出')
    return
  }

  try {
    // 获取用户信息
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    const teacherName = user.teName || user.teacherName || '教师'
    const semester = filterForm.semester || '全部学期'
    
    // 创建CSV内容
    let csvContent = '\uFEFF' // BOM for UTF-8
    
    // 标题行
    csvContent += `教师工作量统计表\n`
    csvContent += `教师姓名：${teacherName}\n`
    csvContent += `统计学期：${semester}\n`
    csvContent += `导出时间：${new Date().toLocaleString('zh-CN')}\n\n`
    
    // 统计概览
    csvContent += `统计概览\n`
    csvContent += `总课时,授课门数,学生人数,平均周课时\n`
    csvContent += `${workloadStats.value.totalHours || 0},${workloadStats.value.courseCount || 0},${workloadStats.value.studentCount || 0},${workloadStats.value.avgWeeklyHours || 0}\n\n`
    
    // 详细统计表头
    csvContent += `详细统计\n`
    csvContent += `序号,课程名称,班级,课程类型,学分,总学时,已完成,剩余,学生数,进度\n`
    
    // 详细数据
    courseDetails.value.forEach((row, index) => {
      csvContent += `${index + 1},${row.courseName},${row.className},${row.courseType},${row.credits},${row.totalHours},${row.completedHours},${row.remainingHours},${row.studentCount},${row.progress}%\n`
    })
    
    // 汇总行
    const totalHours = courseDetails.value.reduce((sum, row) => sum + (row.totalHours || 0), 0)
    const totalCompleted = courseDetails.value.reduce((sum, row) => sum + (row.completedHours || 0), 0)
    const totalRemaining = courseDetails.value.reduce((sum, row) => sum + (row.remainingHours || 0), 0)
    const totalStudents = courseDetails.value.reduce((sum, row) => sum + (row.studentCount || 0), 0)
    
    csvContent += `汇总,共${courseDetails.value.length}条,-,-,-,${totalHours},${totalCompleted},${totalRemaining},${totalStudents},-\n`
    
    // 创建Blob并下载
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    
    const fileName = `教师工作量统计_${teacherName}_${semester}_${new Date().getTime()}.csv`
    link.setAttribute('href', url)
    link.setAttribute('download', fileName)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success('导出成功！')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败: ' + error.message)
  }
}

// 获取进度条颜色
const getProgressColor = (percentage) => {
  if (percentage >= 100) return '#67c23a'
  if (percentage >= 75) return '#409eff'
  if (percentage >= 50) return '#e6a23c'
  return '#f56c6c'
}

// 获取柱状图高度百分比
const getBarHeight = (hours) => {
  const maxHours = Math.max(...weeklyDistribution.value.map(w => w.hours), 1)
  return (hours / maxHours) * 100
}

// 计算汇总行
const getSummaries = (param) => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '汇总'
      return
    }
    if (index === 1) {
      sums[index] = `共 ${data.length} 条`
      return
    }
    
    // 对数值列进行求和
    const values = data.map(item => Number(item[column.property]))
    if (column.property === 'totalHours' || 
        column.property === 'completedHours' || 
        column.property === 'remainingHours' || 
        column.property === 'studentCount') {
      if (!values.every(value => isNaN(value))) {
        const sum = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0)
        sums[index] = sum
      } else {
        sums[index] = '-'
      }
    } else {
      sums[index] = '-'
    }
  })
  return sums
}

// 组件挂载时加载数据
onMounted(() => {
  fetchWorkloadStats()
})
</script>

<style scoped>
.teacher-workload {
  padding: 24px;
  background: #f5f7fa;
  min-height: calc(100vh - 64px);
}

.page-header {
  margin-bottom: 24px;
  text-align: center;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 28px;
  font-weight: 600;
}

/* 筛选卡片 */
.filter-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.filter-form {
  margin: 0;
}

/* 统计概览 */
.stats-overview {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
  font-size: 24px;
}

.stat-icon-calendar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon-reading {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon-user {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon-chart {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  color: #2c3e50;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

/* 详细统计卡片 */
.workload-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

/* 图表卡片 */
.chart-card {
  border-radius: 8px;
}

.chart-card :deep(.el-card__header) {
  background: #f5f7fa;
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.chart-container {
  padding: 20px 0;
}

.bar-chart {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  height: 300px;
  padding: 0 10px;
}

.bar-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.bar-wrapper {
  width: 100%;
  height: 280px;
  display: flex;
  align-items: flex-end;
  justify-content: center;
  padding: 0 4px;
}

.bar {
  width: 100%;
  max-width: 50px;
  background: linear-gradient(180deg, #409eff 0%, #66b1ff 100%);
  border-radius: 4px 4px 0 0;
  position: relative;
  transition: all 0.3s ease;
  min-height: 30px;
}

.bar:hover {
  background: linear-gradient(180deg, #66b1ff 0%, #409eff 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}

.bar-value {
  position: absolute;
  top: -25px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 12px;
  font-weight: 600;
  color: #409eff;
  white-space: nowrap;
}

.bar-label {
  font-size: 12px;
  color: #606266;
  text-align: center;
  white-space: nowrap;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background: #f5f7fa;
  color: #2c3e50;
  font-weight: 600;
}

:deep(.el-table td) {
  color: #606266;
}

:deep(.el-table__row:hover) {
  background: #f5f7fa;
}

/* 进度条样式 */
:deep(.el-progress) {
  display: flex;
  align-items: center;
}

:deep(.el-progress__text) {
  font-size: 12px;
  font-weight: 600;
}

/* 汇总行样式 */
:deep(.el-table__footer-wrapper) {
  font-weight: 600;
  background: #f5f7fa;
}

:deep(.el-table__footer-wrapper .cell) {
  color: #409eff;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stats-overview :deep(.el-col) {
    margin-bottom: 16px;
  }
  
  .bar-chart {
    overflow-x: auto;
  }
}

@media (max-width: 768px) {
  .teacher-workload {
    padding: 16px;
  }
  
  .page-header h2 {
    font-size: 24px;
  }
  
  .stat-value {
    font-size: 24px;
  }
}
</style>
